import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/store/user'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/pages/Home.vue'),
    meta: { title: '瓜子二手车 - 二手车直卖网' }
  },
  {
    path: '/cars',
    name: 'CarList',
    component: () => import('@/pages/CarList.vue'),
    meta: { title: '车辆列表 - 瓜子二手车' }
  },
  {
    path: '/car/:id',
    name: 'CarDetail',
    component: () => import('@/pages/CarDetail.vue'),
    meta: { title: '车辆详情 - 瓜子二手车' },
    props: true
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/pages/Profile.vue'),
    meta: { 
      title: '个人中心 - 瓜子二手车',
      requiresAuth: true 
    }
  },
  {
    path: '/favorites',
    name: 'Favorites',
    component: () => import('@/pages/Favorites.vue'),
    meta: { 
      title: '我的收藏 - 瓜子二手车',
      requiresAuth: true 
    }
  },
  {
    path: '/sell',
    name: 'SellCar',
    component: () => import('@/pages/SellCar.vue'),
    meta: { 
      title: '发布卖车 - 瓜子二手车',
      requiresAuth: true 
    }
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('@/pages/About.vue'),
    meta: { title: '关于我们 - 瓜子二手车' }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/pages/Login.vue'),
    meta: { title: '登录 - 瓜子二手车' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title
  }
  
  // 检查需要认证的路由
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    next('/login')
  } else {
    next()
  }
})

export default router